package com.haiertvbic.tvnow.callback;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;

import com.haiertvbic.tvnow.R;
import com.haiertvbic.tvnow.model.UpdateInfo;
import com.haiertvbic.tvnow.network.EPGWeb;
import com.haiertvbic.tvnow.util.SLog;

public class DownloadTask extends AsyncTask<Object, Object, Object> {

	private static final String TAG = "DownloadTaskS";
	private Context context;
	private UpdateInfo updateInfo;

	private ProgressDialog progressDialog;
	String apkUrl;

	public DownloadTask(Context context, UpdateInfo updateInfo) {
		super();
		this.context = context;
		this.updateInfo = updateInfo;
		apkUrl = context.getFilesDir().getParent() + "/TVNOWONTV.apk";
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progressDialog.setTitle(context.getString(R.string.downloading));
		progressDialog.setProgress(0);
		progressDialog.setMax(100);
		progressDialog.setCancelable(false);
		progressDialog.show();
	}

	@Override
	protected Object doInBackground(Object... arg0) {
		String downLoadUrl = "";
		SLog.d(TAG, "" + downLoadUrl);

		downLoadUrl = downLoadUrl + "&id=" + updateInfo.getId() + "&download=1";
		// downLoadUrl = downLoadUrl + "&id=1&download=1";
		URL url1;
		try {
			url1 = new URL(downLoadUrl);
			HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
			conn.setConnectTimeout(6 * 1000);
			if (conn.getResponseCode() != 200) {
				return null;
			}
			InputStream is = conn.getInputStream();

			SLog.d(TAG,
					"checkVersion---------conn.getContentLength()=="
							+ conn.getContentLength());
			SLog.d(TAG,
					"checkVersion---------conn.getHeaderField()=="
							+ conn.getHeaderField("Content-Length"));
			String totalStr = conn.getHeaderField("Content-Length");
			if (totalStr == null || "".equals(totalStr))
				totalStr = "700000";
			int total = Integer.parseInt(totalStr);
			SLog.d(TAG, "checkVersion---------total==" + total);
			File file = new File(apkUrl);
			SLog.d(TAG, "checkVersion---------apkUrl==" + apkUrl);
			if (file.exists()) {
				file.delete();
			}
			FileOutputStream outStream = new FileOutputStream(file);
			byte[] buffer = new byte[1024];
			int len = -1;
			int count = 0;
			int progress = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
				count += len;
				progress = (int) ((count * 100 / total));
				publishProgress(progress);
			}
			outStream.close();
			is.close();

		} catch (MalformedURLException e) {
			SLog.e(TAG, "e.getMessage() : " + e.getMessage());
		} catch (IOException e) {
			SLog.e(TAG, "e.getMessage() : " + e.getMessage());
		} catch (Exception e) {
			SLog.e(TAG, "e.getMessage() : " + e.getMessage());
		}
		return null;
	}

	@Override
	protected void onProgressUpdate(Object... values) {
		// SLog.d(TAG, "DownloadTask--------onProgressUpdate-----values=="
		// + values[0]);
		super.onProgressUpdate(values);
		progressDialog.setProgress((Integer) values[0]);

	}

	@Override
	protected void onPostExecute(Object result) {
		// TODO Auto-generated method stub
		super.onPostExecute(result);
		progressDialog.dismiss();
		String cmd = "adb shell su";
		try {
			Runtime.getRuntime().exec(cmd);
			cmd = "chmod 777 " + apkUrl;
			Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			e.printStackTrace();
		}
		SLog.d(TAG, "checkVersion---------update---------开始安装");
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		SLog.d(TAG, "checkVersion---------update==" + apkUrl);
		intent.setDataAndType(Uri.fromFile(new File(apkUrl)),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}
}
